<?php


namespace app\api\controller\v1;


//type:0 微信小程序  1:微信app 2:支付小程序 3ride_charge_list支付app
use app\api\model\CouponModel;
use app\api\model\ExchangeModel;
use app\api\model\PayModel;
use app\api\model\ServiceAreaModel;
use app\api\model\SharePayRecordModel;
use app\api\model\UserChargeModel;
use app\api\model\UserChargeRideOrderModel;
use app\api\model\UserDepositOrderModel;
use app\api\model\UserMembershipOrderModel;
use app\api\model\UserModel;
use app\api\model\UserRadingOrderModel;
use app\api\model\UserRideCardOrderModel;
use app\common\controller\UserBaseController;
use app\common\library\AlimpModel;
use app\common\library\DLock;
use app\common\library\StatModel;
use app\common\library\WxmpMsg;
use common;
use ApiOper;
use think\Db;
use think\Exception;
use think\facade\Log;

class WalletController extends UserBaseController
{
    function submit_wxmp_chargeAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'amount' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $amount = $this->argv['amount'];
        global $g_env;
        if ($g_env != 'ONLINE') {
            $amount = 1;
        }

        $ret = (new UserChargeModel())->submit_wxmp($city_id, $userinfo, $amount);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_wxapp_chargeAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'amount' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $amount = $this->argv['amount'];
        global $g_env;
        if ($g_env != 'ONLINE') {
            $amount = 1;
        }

        $ret = (new UserChargeModel())->submit_wxapp($city_id, $userinfo, $amount);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_alipay_chargeAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'amount' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $amount = $this->argv['amount'];
        global $g_env;
        if ($g_env != 'ONLINE') {
            $amount = 1;
        }

        $profit_sharing = false;

        if ($userinfo['id'] == '767a1590775f9ad95a334e90229b6901'){
            $profit_sharing = true;
            $amount = 10;
        }

        $ret = (new UserChargeModel())->sumbit_alipay($city_id,$userinfo, $amount,$profit_sharing);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_alipay_appchargeAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'amount' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $amount = $this->argv['amount'];
        global $g_env;
        if ($g_env != 'ONLINE') {
            $amount = 1;
        }


        $ret = (new UserChargeModel())->sumbit_aliapp($city_id,$userinfo, $amount);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    //记录用户退款， 退款走线下
    function add_charge_refund_recordAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'user_id' => 'optstring',
            'phone' => 'optstring',
            'amount' => 'int',
            'reason_type' => 'int',
            'reason_imgs' => 'array',
            'reason_desc' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = null;
        if (isset($this->argv['user_id'])) {
            $userinfo = (new UserModel())->query_info($this->argv['user_id']);
        } else if (isset($this->argv['phone'])) {
            $userinfo = (new UserModel())->query_info_by_phone($this->argv['phone']);
        }

        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询用户信息失败！");
        }

        if ($this->argv['amount'] <= 0 || $userinfo['balance'] <= 0 || $userinfo['balance'] < $this->argv['amount']) {
            $this->throw_myexception(X_ERROR, "账户余额不足！");
        }

        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        if($this->argv['reason_type'] == 5){
            $l = new DLock('balance_refund_' . $userinfo['id'], 30);

            $cd = [
                'user_id' => $userinfo['id'],
                'is_order_finished' => 0,
            ];

            $list = (new UserRadingOrderModel())->query_list(null, $cd, 0, 1);
            if (!empty($list)) {
                $this->throw_myexception(X_ERROR, "用户正在骑行中！");
            }

            $order_id_array = [];
            try {
                $cd = [
                    'user_id' => $userinfo['id'],
                    'order_state' => USER_CHARGE_ORDER_STATE_FINISHED,
                    'refundable' => 1,
                ];
                $charge_list = (new UserChargeModel())->query_list($cd, 0, 100);

                $total = $this->argv['amount'];
                foreach ($charge_list as $e) {
                    if ($e['amount'] <= 0)
                        continue;
                    $remain = $e['amount'] - $e['refund_amount'];
                    $refund = $total;
                    if ($refund > $remain) {
                        $refund = $remain;
                    }
                    $order_id_array[$e['id']] = $refund;

                    (new UserChargeModel())->submit_refund($e['id'], $refund, "退还用户零钱余额");
                    $total -= $refund;
                    if ($total <= 0) {
                        break;
                    }
                }

//                if($total >0){
//                    $cd2 = [
//                        'user_id' => $userinfo['id'],
//                        'order_state' => USER_CHARGERIDE_ORDER_STATE_FINISHED,
//                        'refundable' => 1,
//                    ];
//                    $charge_ride_list = (new UserChargeRideOrderModel())->query_list($cd2, 0, 100);
//
//                    foreach ($charge_ride_list as $e) {
//                        if ($e['amount'] <= 0)
//                            continue;
//                        $remain = $e['amount'] - $e['refund_amount'];
//                        $refund = $total;
//                        if ($refund > $remain) {
//                            $refund = $remain;
//                        }
//                        $order_id_array[$e['id']] = $refund;
//
//                        (new UserChargeRideOrderModel())->submit_refund($e['id'], $refund, "退还用户零钱余额");
//                        $total -= $refund;
//                        if ($total <= 0) {
//                            break;
//                        }
//                    }
//                }

            } catch (Exception $e) {
                Log::error("refund  balance  user id:" . $userinfo['id'] . ", exception:" . $e->getMessage());
            }
            $this->resp['info'] = $order_id_array;
        }
        else{
            $ret = (new UserChargeModel())->add_refund_record($city_id, $this->argv['amount'], $userinfo, $this->argv['reason_type'], $this->argv['reason_desc'], $this->argv['reason_imgs']);

            (new UserModel())->incr_balance($userinfo['id'], 0 - $this->argv['amount']);

            $this->resp['info'] = $ret;
        }

        return $this->ret_resp();

    }

    function charge_listAction()
    {
        $this->paramlist = [
            'user_id' => 'optstring',
            'pno' => 'optint',
            'psize' => 'optint',
            'start_time' => 'optint'
        ];
        $this->check_params();
        $this->check_token();

        $l = (new UserChargeModel())->query_list($this->argv, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $l;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function ride_charge_listAction()
    {
        $this->paramlist = [
            'user_id' => 'optstring',
            'pno' => 'optint',
            'psize' => 'optint',
            'start_time' => 'optint'
        ];
        $this->check_params();
        $this->check_token();

        $l = (new UserChargeRideOrderModel())->query_list($this->argv, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $l;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function charge_refund_listAction()
    {
        $this->paramlist = [
            'pno' => 'optint',
            'psize' => 'optint',
            'start_time' => 'optdatetime',
            'oper_id' => 'optstring',
        ];

        $this->check_params();
        $this->check_token();

        $cd = $this->argv;
        $cd['is_refund_order'] = 1;

        $l = (new UserChargeModel())->query_list($cd, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $l;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function submit_wxmp_depositAction()
    {
        hilog::set_pay_log_path();
        $this->paramlist = [
        ];

        $amount = 29900;
        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel)->query_info($this->user_info['id']);
        if ($userinfo['deposit'] > 0) {
            $this->throw_myexception(X_ERROR, "已交押金!");
        }
        if ($userinfo['deposit'] < 0) {
            $this->throw_myexception(X_ERROR, "处理押金退款中，请稍后再试!");
        }

        $ret = (new UserDepositOrderModel())->submit_wxmp($userinfo, $amount);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function deposit_listAction()
    {
        $this->paramlist = [
            'user_id' => 'optstring',
            'pno' => 'optint',
            'psize' => 'optint',
        ];
        $this->check_params();
        $this->check_token();

        $l = (new UserDepositOrderModel())->query_list($this->argv, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $l;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function membership_listAction()
    {
        $this->paramlist = [
            'user_id' => 'optstring',
            'pno' => 'optint',
            'psize' => 'optint',
        ];
        $this->check_params();
        $this->check_token();

        $l = (new UserMembershipOrderModel())->query_list($this->city_id, $this->argv, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $l;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function listAction()
    {
        $this->paramlist = [
            'user_id' => 'optstring',
            'pno' => 'optint',
            'psize' => 'optint',
        ];
        $this->check_params();
        $this->check_token();

        $this->argv['no_order_type'] = 'USER_RIDE_CHARGE';
        $l = (new PayModel())->query_list($this->argv, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $l;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function mycouponsAction()
    {
        $this->paramlist = [
            'token' => 'string',
            'pno' => 'int',
            'psize' => 'int',
        ];

        $cd = [
            'state' => 0,
        ];

        $this->check_params();
        $this->check_token();

        $list = (new CouponModel())->query_my_list(ApiOper::instance()->userinfo()['id'], $cd, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function coupons_listAction()
    {
        $this->paramlist = [
            'token' => 'string',
            'user_id' => 'string',
            'pno' => 'int',
            'psize' => 'int',
            'state' => 'optint',            //0表示未使用，100：已使用 101：已退还
            'start_time' => 'optstring',    //生成优惠卷开始时间
            'start_time' => 'optstring',    //生成优惠价结束时间
            'is_out_date' => 'optint',      //是否过期 0：未过期  1：过期
        ];


        $this->check_params();
        $this->check_token();

        $list = (new CouponModel())->query_list($this->argv['user_id'], $this->argv, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }

    function membership_cardsAction()
    {
        $this->paramlist = [
            'token' => 'string',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }
        $this->resp['membership_cards'] = (new UserMembershipOrderModel())->card_list($city_id);

        return $this->ret_resp();
    }

    function my_membership_cardsAction()
    {
        $this->paramlist = [
            'token' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $cd = [
            'user_id' => $this->user_info['id'],
            'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
        ];
        $this->resp['list'] = (new UserMembershipOrderModel())->query_my_list($cd, 0, 20);

        return $this->ret_resp();
    }

    function submit_wxmp_membershipAction()
    {

        //hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $ret = (new UserMembershipOrderModel())->submit_wxmp($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_wxapp_membershipAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $ret = (new UserMembershipOrderModel())->submit_wxapp($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_alipay_membershipAction()
    {

        //hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $ret = (new UserMembershipOrderModel())->submit_alipay($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_alipay_appmembershipAction()
    {

        //hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        $ret = (new UserMembershipOrderModel())->submit_aliapp($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    ////////////////////////////////////////////////////////////////////
    function wxpay_notifyAction(){
        self::wxpay_notify_cityAction(null);
    }
    //贺州
    function wxpay_notify_hezhouAction(){
        self::wxpay_notify_cityAction('451100');
    }

    function wxpay_notify_cityAction($city){
        //hilog::set_pay_log_path();
        $this->encode_type = ENCODE_TYPE_XML;


        $this->resp['return_code'] = 'SUCCESS';
        $this->resp['return_msg'] = 'OK';

        $raw = $this->request->getRawBody();

        //hilog::debug($raw);
        $xml = common::xml_to_array($raw);
        if (empty($xml) || $xml['return_code'] != 'SUCCESS')
            return;

        $xmltmp = $xml;
        unset($xmltmp['sign']);

        $pay_city = 'default';
        if (isset($xml['attach'])){
            $pay_city = $xml['attach'];
        }

        $sign = (new PayModel($pay_city))->wx_sign($xmltmp);
        if ($sign != $xml['sign']) {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = '签名失败';
            return;
        }

        $order_id = $xml['out_trade_no'];
        $lock = new DLock($order_id, 10);

        $wxpay_order_info = (new PayModel())->query_info($order_id);
        if (empty($wxpay_order_info)) {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = '获取订单信息失败！';
            return;
        }
        if (empty($wxpay_order_info)) {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = '获取订单信息失败！';
            return;
        }

        if ($wxpay_order_info['order_state'] == 100) {
            $this->resp['return_code'] = 'SUCCESS';
            $this->resp['return_msg'] = '已支付订单！';
            return;
        }

        if ($wxpay_order_info['amount'] != $xml['total_fee']) {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = '金额不一致！';
            return;
        }

        $out_order_id = $wxpay_order_info['out_order_id'];
        //定金
        if ($wxpay_order_info['order_type'] == ORDER_TYPE_USER_DEPOSIT) {
            $user_deposit_order_info = (new UserDepositOrderModel())->query_info($out_order_id);
            if (empty($user_deposit_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }
            if (empty($user_deposit_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if ($user_deposit_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付订单！';
                return;
            }

            if ($user_deposit_order_info['amount'] != $xml['total_fee']) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '金额不一致！';
                return;
            }
            $payment_info = $xml;
            (new UserDepositOrderModel())->finish($out_order_id, $payment_info);

        }//充值
        else if ($wxpay_order_info['order_type'] == ORDER_TYPE_USER_CHARGE) {
            $user_charge_order_info = (new UserChargeModel())->query_info($out_order_id);
            if (empty($user_charge_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }
            if (empty($user_charge_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if ($user_charge_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付订单！';
                return;
            }

            if ($user_charge_order_info['amount'] != $xml['total_fee']) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '金额不一致！';
                return;
            }
            $payment_info = $xml;
            (new UserChargeModel())->finish($out_order_id, $payment_info);
            $userinfo = (new UserModel())->query_info($wxpay_order_info['user_id']);
            (new WxmpMsg())->send_msg_charge($userinfo['wxmp_open_id'], $wxpay_order_info['prepay_id'], $wxpay_order_info['amount'], $userinfo['balance']);
        } else if ($wxpay_order_info['order_type'] == ORDER_TYPE_USER_MEMBER_SHIP) {
            $membership_order_info = (new UserMembershipOrderModel())->query_info($out_order_id);
            if (empty($membership_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if (empty($membership_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if ($membership_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付订单！';
                return;
            }

            if ($membership_order_info['amount'] != $xml['total_fee']) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '金额不一致！';
                return;
            }
            $payment_info = $xml;
            (new UserMembershipOrderModel())->finish($out_order_id, $payment_info);
        } else if ($wxpay_order_info['order_type'] == ORDER_TYPE_USER_RIDE_CHARGE) {
            $user_charge_ride_order = (new UserChargeRideOrderModel())->query_info($out_order_id);
            if (empty($user_charge_ride_order)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if (empty($user_charge_ride_order)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if ($user_charge_ride_order['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付订单！';
                return;
            }

            if ($user_charge_ride_order['amount'] != $xml['total_fee']) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '金额不一致！';
                return;
            }
            $payment_info = $xml;
            (new UserChargeRideOrderModel())->finish($out_order_id, $payment_info);
        } else if ($wxpay_order_info['order_type'] == ORDER_TYPE_USER_RIDECARD) {
            $ridecard_order_info = (new UserRideCardOrderModel())->query_info($out_order_id);
            if (empty($ridecard_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if (empty($ridecard_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取订单信息失败！';
                return;
            }

            if ($ridecard_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付订单！';
                return;
            }

            if ($ridecard_order_info['amount'] != $xml['total_fee']) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '金额不一致！';
                return;
            }
            $payment_info = $xml;
            (new UserRideCardOrderModel())->finish($out_order_id, $payment_info);
        }
        else {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = 'query order error！';
            return;
        }
        (new PayModel())->finish($order_id, $xml['transaction_id'], $xml);

        return $this->ret_resp();
    }

    ////////////////////////////////////////////////////////////////////
    ///
    //退款
    function wxpay_refund_notifyAction(){
        self::wxpay_refund_notify_cityAction(null);
    }

    function wxpay_refund_notify_hezhouAction(){
        self::wxpay_refund_notify_cityAction('451100');
    }

    function wxpay_refund_notify_cityAction($city)
    {

       //hilog::set_pay_log_path();
        $this->encode_type = ENCODE_TYPE_XML;


        $this->resp['return_code'] = 'SUCCESS';
        $this->resp['return_msg'] = 'OK';

        $raw = $this->request->getRawBody();

        //hilog::debug($raw);
        $xml = common::xml_to_array($raw);
        if (empty($xml) || $xml['return_code'] != 'SUCCESS')
            return;


        $req_info = $xml['req_info'];
        $req_xml_str = (new PayModel($city))->wxpay_decrypt($req_info);

        //hilog::debug("wxpay_decrypt", $req_info, $req_xml_str);

        $req_xml = common::xml_to_array($req_xml_str);
        $out_refund_no = $req_xml['out_refund_no'];
        $wxpay_order_id = $req_xml['out_trade_no'];

        $wxpay_refund_order_info = (new PayModel())->query_info($out_refund_no);
        if (empty($wxpay_refund_order_info)) {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = '获取支付订单信息失败！';
            return;
        }

        if ($wxpay_refund_order_info['order_state'] == 100) {
            $this->resp['return_code'] = 'SUCCESS';
            $this->resp['return_msg'] = '支付订单已完成！';
            return;
        }

        if ($wxpay_refund_order_info['amount'] != 0 - $req_xml['refund_fee']) {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = '支付订单金额不一致！';
            return;
        }

        $wxpay_order_info = (new PayModel())->query_info($wxpay_order_id);

        $out_order_id = $wxpay_order_info['out_order_id'];

        if ($wxpay_refund_order_info['order_type'] == ORDER_TYPE_USER_DEPOSIT_REFUND) {
            $user_deposit_order_info = (new UserDepositOrderModel())->query_info($out_order_id);
            if (empty($user_deposit_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取押金订单信息失败！';
                return;
            }

            if ($user_deposit_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付押金订单！';
                return;
            }
            (new UserDepositOrderModel())->refund_finish($out_order_id, null);
        } else if ($wxpay_refund_order_info['order_type'] == ORDER_TYPE_USER_CHARGE_REFUND) {
            $user_charge_order_info = (new UserChargeModel())->query_info($out_order_id);
            if (empty($user_charge_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取充值订单信息失败！';
                return;
            }

            if ($user_charge_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付押金订单！';
                return;
            }
            (new UserChargeModel())->refund_finish($out_order_id, null);
        } else if ($wxpay_refund_order_info['order_type'] == ORDER_TYPE_USER_MEMBER_SHIP_REFUND) {
            $user_charge_order_info = (new UserMembershipOrderModel())->query_info($out_order_id);
            if (empty($user_charge_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取会员订单信息失败！';
                return;
            }

            if ($user_charge_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付会员订单！';
                return;
            }
            (new UserMembershipOrderModel())->refund_finish($out_order_id, null);
        }
        else if ($wxpay_refund_order_info['order_type'] == ORDER_TYPE_USER_RIDE_CHARGE_REFUND) {
            $user_charge_order_info = (new UserChargeRideOrderModel())->query_info($out_order_id);
            if (empty($user_charge_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取充值订单信息失败！';
                return;
            }

            if ($user_charge_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付押金订单！';
                return;
            }
            (new UserChargeRideOrderModel())->refund_finish($out_order_id, null);
        }else if ($wxpay_refund_order_info['order_type'] == ORDER_TYPE_USER_RIDECARD_REFUND) {
            $user_charge_order_info = (new UserRideCardOrderModel())->query_info($out_order_id);
            if (empty($user_charge_order_info)) {
                $this->resp['return_code'] = 'FAIL';
                $this->resp['return_msg'] = '获取会员订单信息失败！';
                return;
            }

            if ($user_charge_order_info['order_state'] == 100) {
                $this->resp['return_code'] = 'SUCCESS';
                $this->resp['return_msg'] = '已支付会员订单！';
                return;
            }
            (new UserRideCardOrderModel())->refund_finish($out_order_id, null);
        }
        else {
            $this->resp['return_code'] = 'FAIL';
            $this->resp['return_msg'] = '订单类型错误！';
            return;
        }
        (new PayModel())->finish($out_refund_no, $req_xml['refund_id'], $req_xml);

        return $this->ret_resp();
    }

    ////////////////////////////////////////////////////////////////////

    function deposit_refundAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
        ];

        $this->check_params();
        $this->check_token();


        $lock = new DLock('deposit_refun' . $this->user_info['id'], 60);

        $userinfo = (new UserModel())->query_info($this->user_info['id']);
        if ($userinfo['deposit'] <= 0) {
            $this->throw_myexception(X_ERROR, "用户未交押金！");
        }

        $cd = [
            'user_id' => ApiOper::instance()->userinfo()['id'],
            'is_order_finished' => 0,
        ];

        $list = (new UserRadingOrderModel())->query_list(null, $cd, 0, 1);
        if (!empty($list)) {
            $this->throw_myexception(X_ERROR, "用户正在骑行中！");
        }

        (new UserDepositOrderModel())->refund_submit($userinfo['deposit_order_id']);

        return $this->ret_resp();
    }

    function testAction()
    {
        $s = '90XVOr72h8QMxjuwznc1nU2T7uRbf7HmQ+avW6RUFGAiVHNh3SZ+X65sykBfU/B039D4NAkcyYqINUkAY7sawMPpnbJiYU/SKM4nO5PPWa+BSG4eIhNRznP8BMFx+JoIv5c8Vw0j4hJ5XT7VfpWg2V/63l+NJ4XQ8lraRTGmnKoBa5nl17P80DUkME3lNuPjMt0tCaNQV0tmmoevoX31Mx0NLr4OoEaLwOS36JQ1hQw0tfT1iGcrqDy9OIaS2ePFSp9e+46pKZcz6Xault7D6ly0PxTHbp4ETLhQYor8o2a21ePFAR6tXorHpENvf42FDfz1rmGgF74BQ9qzTtraqvLnsspeDYesw7KxycP6JVWxOFkQqSrWLiQZMbYVKX0MGo19mKv8Kfr1jEUuhLAQxK/2fPWS/crGsrJJP3blIOzWNbMoqRMitOQ6h7gdhAZQmFMUKxS6uUjtp1N6x2EhB0JGCfVDudljVpo1hbaQ7FgybY2vgcFaiEvJELwc18dIA0h7JpNiFQoO/cs6WoBotdt1tb8uRjTIWW17yNST1+ukK4bVnAzoErrhw1EQHYhKbvSRsny9bIt5hcecU0UN93k6byzC8/WqQ/sgy8Fs33CmqawVZCdH7pDHeJ4yKC5S0v7IJFntPEX2TH7DWTq7b/6q1pPHzoB9nDn/RC7AQ0PAJa5z2Y9B2NJ1U67MxvV4CES4se5qpwH0CqroZq6b9ZISdDVogPbqmDiJILFG628ETGZYl5FL+XwUMDmhkTQpIF7M9Ve08s4F6vG9O7zLCPxny76Ra0/U77rolWEL5DJD7iPLRPC76Xo2UM0od14Oplb2vcyhpVUNmPLAGqr6vZJN/YrunlDX1I3ToXICMW+SU3JM+K01K8L03J2+Ft/SDy/qnNF7WNYwsscd5XxS4anOh2f3KHLWRSaFmJ/qZ0/Zw/ZxI6AFFD2OyR4+SCIGFwzkaQ1aMr06cwDpsJuelqaOE17YpC0dfZHL/zZpgNZleUyVBJ00WfPyxM1QkK0zN69L0x495ab/OOy5kiS+qXGaOPUL6SJrppRxhEp8WmApMdexyEa9m+EMgW2frTXdaQ352yyXUden7AAk4RTrCg==';
        $req_xml_str = (new PayModel())->wxpay_decrypt($s);
        //hilog::debug('REQ_INFO:', $req_xml_str);
        echo $req_xml_str;
    }

    ////////////////////////////////////////////////////////////////////
    /// 支付宝
    function alipay_notifyAction(){
        self::alipay_notify_cityAction(null);
    }

    function alipay_notify_hezhouAction(){
        self::alipay_notify_cityAction('451100');
    }

    function alipay_notify_cityAction($city_id)
    {

        //hilog::set_pay_log_path();
        $this->encode_type = ENCODE_TYPE_RAW;
        //hilog::debug($_POST);
        $data = $_POST;


        $result = (new AlimpModel($city_id))->create_trade_notify_verify($data);
        if (empty($result)) {
            echo "签名校验失败！";
            return;
        }

        $l = new DLock($data['out_trade_no'], 10);

        $order_id = $data['out_trade_no'];
        if ($data['trade_status'] != 'TRADE_FINISHED' && $data['trade_status'] != 'TRADE_SUCCESS') {
            echo "支付失败!";
            return;
        }


        unset($data['sign']);
        unset($data['sign_type']);

        $pay_order_info = (new PayModel())->query_info($order_id);
        if (empty($pay_order_info)) {
            echo "查询订单信息失败！";
            return;
        }

        if ($pay_order_info['order_state'] == 100) {
            echo "success";
            return;
        }

        if ($pay_order_info['amount'] / 100 != $data['total_amount']) {
            echo "金额不一致!";
            return;
        }

        $out_order_id = $pay_order_info['out_order_id'];
        if ($pay_order_info['order_type'] == ORDER_TYPE_USER_MEMBER_SHIP) {
            $membership_order_info = (new UserMembershipOrderModel())->query_info($out_order_id);

            if ($membership_order_info['order_state'] == USER_MEMBERSHIP_ORDER_STATE_FINISHED) {
                echo "金额不一致!";
                return;
            }
            $payment_info = $data;
            (new UserMembershipOrderModel())->finish($out_order_id, $payment_info);
            echo 'success';
        } else if ($pay_order_info['order_type'] == ORDER_TYPE_USER_CHARGE) {
            $user_charge_order_info = (new UserChargeModel())->query_info($out_order_id);

            if ($user_charge_order_info['order_state'] == USER_MEMBERSHIP_ORDER_STATE_FINISHED) {
                echo "金额不一致!";
                return;
            }
            $payment_info = $data;
            (new UserChargeModel())->finish($out_order_id, $payment_info);
            echo 'success';
        }
        else if ($pay_order_info['order_type'] == ORDER_TYPE_USER_RIDE_CHARGE) {
            $user_charge_order_info = (new UserChargeRideOrderModel())->query_info($out_order_id);

            if ($user_charge_order_info['order_state'] == USER_CHARGERIDE_ORDER_STATE_FINISHED) {
                echo "金额不一致!";
                return;
            }
            $payment_info = $data;
            (new UserChargeRideOrderModel())->finish($out_order_id, $payment_info);
            echo 'success';
        }
        else  if ($pay_order_info['order_type'] == ORDER_TYPE_USER_RIDECARD) {
            $ride_order_info = (new UserRideCardOrderModel())->query_info($out_order_id);

            if ($ride_order_info['order_state'] == USER_RIDECARD_ORDER_STATE_FINISHED) {
                echo "金额不一致!";
                return;
            }
            $payment_info = $data;
            (new UserRideCardOrderModel())->finish($out_order_id, $payment_info);
            echo 'success';
        }

        (new PayModel())->finish($order_id, $data['trade_no'], $data);

        return $this->ret_resp();
    }

    ////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////
    /// 支付宝退款
    function alipay_refund_notifyAction()
    {
        self::alipay_notify_cityAction(null);
    }

    function alipay_refund_notify_hezhouAction()
    {
        self::alipay_notify_cityAction('451100');
    }

    function alipay_refund_notify_cityAction($city_id)
    {

        //hilog::set_pay_log_path();
        $this->encode_type = ENCODE_TYPE_RAW;
        //hilog::debug($_POST);
        $data = $_POST;


        $result = (new AlimpModel($city_id))->create_trade_notify_verify($data);
        if (empty($result)) {
            echo "签名校验失败！";
            return;
        }

    }

    function bat_refund_balanceAction()
    {
       // hilog::set_pay_log_path();
        $this->paramlist = [
            'phone' => ['optstring', '15980198199'],
            'token' => ['optstring', 'SUOZHANGBIEKAIQIANG'],
        ];

        $this->check_params();
        $this->check_token();
        $city_id = '350001';
        $cd = [
            'to_refund_charge' => 1,
        ];

        $order_id_array = [];
        $user_list = (new UserModel())->get_list($city_id, $cd, 0, 100);


        foreach ($user_list as $userinfo) {
            $l = new DLock('balance_refund_' . $userinfo['id'], 30);
            try {
                $cd = [
                    'user_id' => $userinfo['id'],
                    'is_order_finished' => 0,
                ];

                $pos = rand(0, 50);
                $list = (new UserRadingOrderModel())->query_list(null, $cd, $pos, 1);
                if (!empty($list)) {
                    $this->throw_myexception(X_ERROR, "用户正在骑行中！");
                }

                if ($userinfo['balance'] > 0) {
                    $cd = [
                        'user_id' => $userinfo['id'],
                        'order_state' => USER_CHARGE_ORDER_STATE_FINISHED,
                        'refundable' => 1,
                    ];
                    $charge_list = (new UserChargeModel())->query_list($cd, 0, 100);

                    $total = $userinfo['balance'];
                    foreach ($charge_list as $e) {
                        if ($e['amount'] <= 0)
                            continue;

                        $order_id_array[$userinfo['id']][] = $e['id'];
                        $remain = $e['amount'] - $e['refund_amount'];
                        $refund = $total;
                        if ($refund > $remain) {
                            $refund = $remain;
                        }

                        (new UserChargeModel())->submit_refund($e['id'], $refund, "退还用户零钱余额");
                        $total -= $refund;
                        if ($total <= 0) {
                            break;
                        }
                    }
                }
            } catch (Exception $e) {

                Log::error("refund  balance  user id:" . $userinfo['id'] . ", exception:" . $e->getMessage());
            }
        }
        //$userinfo = UserModel::instance()->query_info_by_phone($this->argv['phone']);

        $this->resp['orders'] = $order_id_array;

        return $this->ret_resp();
    }

    function bat_refund_membershipAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'phone' => ['optstring', '15980198199'],
            'token' => ['optstring', 'SUOZHANGBIEKAIQIANG'],
        ];

        $this->check_params();
        $this->check_token();

        $city_id = '350001';
        $cd = [
            'to_refund_membership' => 1,
        ];

        $order_id_array = [];

        $user_list = (new UserModel())->get_list($city_id, $cd, 0, 30);
        foreach ($user_list as $userinfo) {

            $l = new DLock('membership_refund_' . $userinfo['id'], 30);
            $order_id_array[$userinfo['id']] = [];
            // $userinfo = UserModel::instance()->query_info_by_phone($this->argv['phone']);
            try {
                $cd = [
                    'user_id' => $userinfo['id'],
                    'is_order_finished' => 0,
                ];

                $list = (new UserRadingOrderModel())->query_list(null, $cd, 0, 1);
                if (!empty($list)) {
                    $this->throw_myexception(X_ERROR, "用户正在骑行中！");
                }

                $cd = [
                    'user_id' => $userinfo['id'],
                    'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
                ];


                $effect_order_id_arr = [];
                $order_list = (new UserMembershipOrderModel())->query_my_list($cd, 0, 10);
                foreach ($order_list as $e) {
                    if ($e['amount'] <= 0)
                        continue;

                    $effect_order_id_arr[] = $e['id'];
                    $order_id_array[$userinfo['id']][] = $e['id'];
                    (new UserMembershipOrderModel())->summit_refund($e['id'], $e['amount'], "免押金卡退款");
                }
            } catch (Exception $e) {
                Log::error("refund charge  user id:" . $userinfo['id'] . ", exception:" . $e->getMessage());
            }

        }

        $this->resp['orders'] = $order_id_array;

        return $this->ret_resp();
    }

    function refund_balanceAction()
    {
        $this->paramlist = [
            'user_id' => 'string',
            'amount' => 'int',
        ];

        $this->check_params();
        $this->check_token();
        if (ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_OPS &&ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CC && ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CS) {
            $this->throw_myexception(X_ERROR, 'shit');
        }

        if (ApiOper::instance()->userinfo()['user_type'] == OPER_TYPE_OPS
            &&ApiOper::instance()->userinfo()['ops_role_id'] != STAFF_ROLE_SUPER_ADMIN){
            $this->throw_myexception(X_ERROR, "没有权限！");
        }

        $userinfo = (new UserModel())->query_info($this->argv['user_id']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        if ($this->city_id && $this->city_id != $userinfo['city_id']) {
            $this->throw_myexception(X_ERROR, "没有权限！");
        }


        if ($this->argv['amount'] <= 0 || $this->argv['amount'] > $userinfo['balance']) {
            $this->throw_myexception(X_ERROR, "金额错误！");
        }

        $l = new DLock('balance_refund_' . $userinfo['id'], 30);

        $cd = [
            'user_id' => $userinfo['id'],
            'is_order_finished' => 0,
        ];

        $list = (new UserRadingOrderModel())->query_list(null, $cd, 0, 1);
        if (!empty($list)) {
            $this->throw_myexception(X_ERROR, "用户正在骑行中！");
        }

        $order_id_array = [];
        try {
            $cd = [
                'user_id' => $userinfo['id'],
                'order_state' => USER_CHARGE_ORDER_STATE_FINISHED,
                'refundable' => 1,
            ];
            $charge_list = (new UserChargeModel())->query_list($cd, 0, 100);

            $total = $this->argv['amount'];
            foreach ($charge_list as $e) {
                if ($e['amount'] <= 0)
                    continue;
                $remain = $e['amount'] - $e['refund_amount'];
                $refund = $total;
                if ($refund > $remain) {
                    $refund = $remain;
                }
                $order_id_array[$e['id']] = $refund;

                (new UserChargeModel())->submit_refund($e['id'], $refund, "退还用户零钱余额");
                $total -= $refund;
                if ($total <= 0) {
                    break;
                }
            }

//            if($total >0){
//                $cd2 = [
//                    'user_id' => $userinfo['id'],
//                    'order_state' => USER_CHARGERIDE_ORDER_STATE_FINISHED,
//                    'refundable' => 1,
//                ];
//                $charge_ride_list = (new UserChargeRideOrderModel())->query_list($cd, 0, 100);
//
//                foreach ($charge_ride_list as $e) {
//                    if ($e['amount'] <= 0)
//                        continue;
//                    $remain = $e['amount'] - $e['refund_amount'];
//                    $refund = $total;
//                    if ($refund > $remain) {
//                        $refund = $remain;
//                    }
//                    $order_id_array[$e['id']] = $refund;
//
//                    (new UserChargeRideOrderModel())->submit_refund($e['id'], $refund, "退还用户零钱余额");
//                    $total -= $refund;
//                    if ($total <= 0) {
//                        break;
//                    }
//                }
//            }

        } catch (Exception $e) {
            Log::error("refund  balance  user id:" . $userinfo['id'] . ", exception:" . $e->getMessage());
        }

        return $this->ret_resp();
    }

    function refund_membershipAction()
    {
        $this->paramlist = [
            'user_id' => 'string',
        ];

        $this->check_params();
        $this->check_token();
        if (ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CC && ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CS && ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_OPS) {
            $this->throw_myexception(X_ERROR, 'shit');
        }

        if (ApiOper::instance()->userinfo()['user_type'] == OPER_TYPE_OPS
            &&ApiOper::instance()->userinfo()['ops_role_id'] != STAFF_ROLE_SUPER_ADMIN){
            $this->throw_myexception(X_ERROR, "没有权限！");
        }

        $userinfo = (new UserModel())->query_info($this->argv['user_id']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        if ($this->city_id && $this->city_id != $userinfo['city_id']) {
            $this->throw_myexception(X_ERROR, "没有权限！");
        }

        $l = new DLock('membership_refund_' . $userinfo['id'], 30);

        $cd = [
            'user_id' => $userinfo['id'],
            'is_order_finished' => 0,
        ];

        $list = (new UserRadingOrderModel())->query_list(null, $cd, 0, 1);
        if (!empty($list)) {
            $this->throw_myexception(X_ERROR, "用户正在骑行中！");
        }


        $order_id_array = [];
        $amount = 0;
        try {
            $cd = [
                'user_id' => $userinfo['id'],
                'order_state' => USER_MEMBERSHIP_ORDER_STATE_FINISHED,
            ];

            $effect_order_id_arr = [];
            $order_list = (new UserMembershipOrderModel())->query_my_list($cd, 0, 1);
            foreach ($order_list as $e) {
                if ($e['amount'] <= 0)
                    continue;

                $effect_order_id_arr[] = $e['id'];
                $order_id_array[$userinfo['id']][] = $e['id'];
                (new UserMembershipOrderModel())->summit_refund($e['id'], $e['amount'], "会员卡退款");
                $amount += $e['amount'];
            }
        } catch (Exception $e) {
            Log::error("refund  balance  user id:" . $userinfo['id'] . ", exception:" . $e->getMessage());
        }
        $this->resp['amount'] = $amount;

        return $this->ret_resp();
    }

    function refund_membershipbyorderAction()
    {
        $this->paramlist = [
            'user_id' => 'string',
            'order_id' => 'string',
        ];

        $this->check_params();
        $this->check_token();
        if (ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CC && ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CS && ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_OPS) {
            $this->throw_myexception(X_ERROR, 'shit');
        }
//
//        if (ApiOper::instance()->userinfo()['user_type'] == OPER_TYPE_OPS
//            &&ApiOper::instance()->userinfo()['ops_role_id'] != STAFF_ROLE_SUPER_ADMIN){
//            throw_myexception(X_ERROR, "没有权限！");
//        }

        $userinfo = (new UserModel())->query_info($this->argv['user_id']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        if ($this->city_id && $this->city_id != $userinfo['city_id']) {
           $this->throw_myexception(X_ERROR, "没有权限！");
        }

        $l = new DLock('membership_refund_' . $userinfo['id'], 30);

        $cd = [
            'user_id' => $userinfo['id'],
            'is_order_finished' => 0,
        ];

        $list = (new UserRadingOrderModel())->query_list(null, $cd, 0, 1);
        if (!empty($list)) {
            $this->throw_myexception(X_ERROR, "用户正在骑行中！");
        }

        $order_id_array = [];
        $amount = 0;
        try {
            $order_info = (new UserMembershipOrderModel())->query_info($this->argv['order_id']);
            if($order_info){
                if ($order_info['amount'] <= 0)
                    $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败");

                if($order_info['order_state'] != USER_MEMBERSHIP_ORDER_STATE_FINISHED)
                    $this->throw_myexception(ERROR_QUERY_INFO, "订单未完成");

                (new UserMembershipOrderModel())->summit_refund($order_info['id'], $order_info['amount'], "会员卡退款");
                $amount += $order_info['amount'];
            }
        } catch (Exception $e) {
            Log::error("refund  balance  user id:" . $userinfo['id'] . ", exception:" . $e->getMessage());
        }
        $this->resp['amount'] = $amount;

        return $this->ret_resp();
    }

    //骑行卡退款
    function refund_ridecardAction()
    {
        $this->paramlist = [
            'token' => 'string',
            'user_id' => 'string',      //玩家id
        ];

        $this->check_params();
        $this->check_token();
        if (ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CC && ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_CS && ApiOper::instance()->userinfo()['user_type'] != OPER_TYPE_OPS) {
            $this->throw_myexception(X_ERROR, 'shit');
        }

//        if (ApiOper::instance()->userinfo()['user_type'] == OPER_TYPE_OPS
//            &&ApiOper::instance()->userinfo()['ops_role_id'] != STAFF_ROLE_SUPER_ADMIN){
//            throw_myexception(X_ERROR, "没有权限！");
//        }

        $userinfo = (new UserModel())->query_info($this->argv['user_id']);
        if (empty($userinfo)) {
           $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

//        if ($this->city_id && $this->city_id != $userinfo['city_id']) {
//            throw_myexception(X_ERROR, "没有权限！");
//        }

        $l = new DLock('ridecard_refund_' . $userinfo['id'], 30);

        $cd = [
            'user_id' => $userinfo['id'],
            'is_order_finished' => 0,
        ];

        $list = (new UserRadingOrderModel())->query_list(null, $cd, 0, 1);
        if (!empty($list)) {
            $this->throw_myexception(X_ERROR, "用户正在骑行中！");
        }


        $amount = 0;
        try {
            $cd = [
                'user_id' => $userinfo['id'],
                'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
                'is_use' => 1,
            ];

            $effect_order_id_arr = [];
            $order_list = (new UserRideCardOrderModel())->query_my_list($cd, 0, 1);
            foreach ($order_list as $e) {
                if ($e['amount'] <= 0)
                    continue;

                if ($e['free_count'] != $e['free_count_total'] )
                    $this->throw_myexception(X_ERROR, "已经使用过骑行卡，无法退卡！");


                (new UserRideCardOrderModel())->summit_refund($e['id'], $e['amount'], "骑行卡退款");
                $amount += $e['amount'];
            }
        } catch (Exception $e) {
            Log::error("refund  balance  user id:" . $userinfo['id'] . ", exception:" . $e->getMessage());
        }
        $this->resp['amount'] = $amount;

        return $this->ret_resp();
    }

    //用户结算订单
    function pay_orderAction(){
       // hilog::set_pay_log_path();
        $this->paramlist = [
            'token' => 'string',
            'order_id' => 'string',
            'coup_id' => 'string',
//            'amount' => 'float',
            'channel' => 'string',
            'usescore' => ['optint',0],
        ];

        $this->check_params();
        $this->check_token();

        $order_id = $this->argv['order_id'];

        $lock = new DLock($order_id, 60);

        $order_info = null;
        if (empty($order_id)){
            $cd = [
                'user_id' => ApiOper::instance()->userinfo()['id'],
                'is_order_finished' => 1,
                'is_pay' => 0,
            ];
            $list = (new UserRadingOrderModel())->query_paying_list(null, $cd, 0, 1);
            if (empty($list)) {
                $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败");
            }
            else {
                $order_id = $list[0]['id'];
            }
        }

        $order_info = (new UserRadingOrderModel())->query_fee_info(null, $order_id);

        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败");
        }
        if ($order_info['order_state'] != RIDE_ORDER_STATE_FINISH) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        if ($order_info['is_pay'] == 1) {
            $this->throw_myexception(ERROR_QUERY_INFO, "订单已支付!");
        }

//        $amount = $this->argv['amount'];
//        global $g_env;
//        if ($g_env != 'ONLINE') {
//            $amount = 1;
//        }

        $channel = $this->argv['channel'];
        if (empty($channel)){
            $channel = ApiOper::instance()->userinfo()['channel'];
        }

        $user_data = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $user_data['city_id'];

        $fee_info = $order_info['fee_info'];


        //优惠
        if (!empty($this->argv['coup_id'])){
            $coupon_info = (new CouponModel())->query_info($this->argv['coup_id']);
            if ($coupon_info){
                $couopon_amount = (new CouponModel())->coupon_amount($coupon_info);
                if ($couopon_amount >0){
                    if ($coupon_info['type'] == 1) {
                        if ($couopon_amount > 0 && $fee_info['no_coupon_fee'] < $couopon_amount) {
                            $couopon_amount = $fee_info['no_coupon_fee'];
                        }

                        $fee_info['coupon_id'] = $coupon_info['id'];
                        $fee_info['coupon_metadata'] = $coupon_info['metadata'];
                        $fee_info['coupon_fee'] = $couopon_amount;
                    } elseif ($coupon_info['type'] == 2) {
                        $calc_amount = $fee_info['no_coupon_fee'] - ceil($couopon_amount/100*$fee_info['no_coupon_fee']);
                        if ($calc_amount > 0 && $fee_info['no_coupon_fee'] < $calc_amount) {
                            $calc_amount = $fee_info['no_coupon_fee'];
                        }
                        else {
                            $calc_amount = 0;
                        }

                        $fee_info['coupon_id'] = $coupon_info['id'];
                        $fee_info['coupon_metadata'] = $coupon_info['metadata'];
                        $fee_info['coupon_fee'] = $calc_amount;
                    }
                }

            }

        }


        $fee_info['total'] -= $fee_info['coupon_fee'];
        $need_score = 0;

        //使用积分
        if ($this->argv['usescore'] == 1 && $fee_info['total'] > 0){
            if (isset($fee_info['score_need']) && $fee_info['score_need'] >0 && isset($fee_info['score_fee']) && $fee_info['score_fee'] >0) {

                $need_score = ceil($fee_info['total'] * $fee_info['score_fee']/100);

                if ($need_score <= $fee_info['score_need']) {
                    $fee_info['score_need'] = $need_score;
                }
                else{
                    $need_score = $fee_info['score_need'];
                }

                if ($user_data['score'] < $fee_info['score_need']) {
                    $this->throw_myexception(ERROR_QUERY_INFO, "积分不足，无法兑换!");
                }

                $score_fee = ceil($fee_info['score_need'] *100 / $fee_info['score_fee']);
                $fee_info['total'] -= $score_fee;
            }
        }

        if ($fee_info['total'] < 0){
            $fee_info['total'] = 0;
        }


        $tmpamount = $fee_info['total'];

        if ($fee_info['total'] > $user_data['balance']){
            if ($user_data['balance'] >0){
                $tmpamount = $fee_info['total'] - $user_data['balance'];
            }

            $ret = null;
            if($tmpamount > 0){
                $may_amount = 0;
                if ($tmpamount > 0){
                    $now = date('Y-m-d H:i:s');
                    $begin_time = "2020-05-01 00:00:00";
                    $end_time = "2020-05-05 23:59:59";

                    if((strtotime($now) - strtotime($begin_time) >=0)&&(strtotime($now) - strtotime($end_time) <=0)){
                        $may_amount = common::get_may_amount();
                        $this->resp['may_amount'] = $may_amount;
                    }
                }

                if ($channel == 'wxmpu'){
                    $ret = (new UserChargeRideOrderModel())->submit_wxmp($order_info['city_id'], $user_data, $tmpamount,$order_id,$this->argv['coup_id'],$may_amount,$need_score);
                }
                else{
                    $ret = (new UserChargeRideOrderModel())->submit_alipay($order_info['city_id'], $user_data, $tmpamount,$order_id,$this->argv['coup_id'],$may_amount,$need_score);
                }
            }

            $this->resp['is_wallet'] = 0;
            $this->resp['info'] = $ret;
        }
        else {
            //余额结账
            //优惠
            $fee_info['balance_fee'] = $fee_info['total'];

            if($fee_info['total'] > 0)
                (new UserModel())->incr_balance($order_info['user_id'], 0 - $fee_info['total']);

            //计算积分
            if ($this->argv['usescore'] == 1){
                if (isset($fee_info['score_need']) && $fee_info['score_need'] >0 && isset($fee_info['score_fee']) && $fee_info['score_fee'] >0) {
                    (new UserModel())->incr_score($order_info['user_id'], 0 - $fee_info['score_need']);

                    //记录一下
                    (new ExchangeModel())->record($city_id,$user_data,SCORE_GATEWAY_RIDEPAY,-$fee_info['score_need']);
                }
            }
            else{
                $fee_info['score_need'] = 0;
            }


            $data = [
                'coupon_id' => $fee_info['coupon_id'],
                'coupon_metadata' => $fee_info['coupon_metadata'],
                'distance' => $fee_info['distance'],
                'is_flush' => $fee_info['is_flush'],
                'paid_amount' => $fee_info['total'],
                'fee_info' => $fee_info,
                'violation_fine' => $fee_info['npa_fee'] + $fee_info['osvc_fee'],
                'is_pay'=>1,
            ];


            $where = [
                'id' => $order_id,
            ];


            Db::table('tb_user_ride_order')->where($where)->update($data);
            //hisql::update('tb_user_ride_order', $data, $where);

            if($data['is_pay'] == 1){
                //支付完成
                (new PayModel())->add_record($city_id, $order_info['user_id'], ORDER_TYPE_USER_RIDE, $order_id, PAY_GATEWAY_WALLET, $fee_info['total']);
            }

            if ($fee_info['npa_fee'] > 0 || $fee_info['osvc_fee'] > 0) {
                (new UserModel())->incr_violation_count($order_info['user_id']);
            }

            if ($data['coupon_id'] && $data['is_pay'] == 1) {
                (new CouponModel())->perform($data['coupon_id'],$order_id);

                //添加日志
                if($fee_info['coupon_fee'] >0)
                    (new StatModel())->user_ride_order_amount_incr($order_info['city_id'], $order_info['create_time'], -$fee_info['coupon_fee'],$order_info['start_svca_id']);
            }

            if ($data['is_pay'] == 1){
                $now = date('Y-m-d H:i:s');
                $begin_time = "2020-05-01 00:00:00";
                $end_time = "2020-05-05 23:59:59";

                if((strtotime($now) - strtotime($begin_time) >=0)&&(strtotime($now) - strtotime($end_time) <=0)){
                    if($data['is_pay'] == 1){
                        $may_amount = common::get_may_amount();
                        (new CouponModel())->create_coupon_May_Day($may_amount,$order_info['user_id'],'五一感恩前行');
                        $this->resp['may_amount'] = $may_amount;
                    }
                }
            }

            $this->resp['is_wallet'] = 1;
        }

        $score_info =[
            'score_need' => $need_score,
            'score_fee'  => isset($fee_info['score_fee'])?$fee_info['score_fee']:0,
        ];

        $this->resp['score_info'] = $score_info;

        return $this->ret_resp();
    }

    //用户结算订单
    function pay_orderappAction(){
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'token' => 'string',
            'order_id' => 'string',
            'coup_id' => 'string',
//            'amount' => 'float',
            'channel' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $order_id = $this->argv['order_id'];
        $order_info = null;
        if (empty($order_id)){
            $cd = [
                'user_id' => ApiOper::instance()->userinfo()['id'],
                'is_order_finished' => 1,
                'is_pay' => 0,
            ];
            $list = (new UserRadingOrderModel())->query_paying_list(null, $cd, 0, 1);
            if (empty($list)) {
                $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败");
            }
            else {
                $order_id = $list[0]['id'];
            }
        }

        $order_info = (new UserRadingOrderModel())->query_fee_info(null, $order_id);

        if (empty($order_info)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "查询订单失败");
        }
        if ($order_info['order_state'] != RIDE_ORDER_STATE_FINISH) {
            $this->throw_myexception(ERROR_STATE_DISMATCH, "订单状态不匹配!");
        }

        if ($order_info['is_pay'] == 1) {
            $this->throw_myexception(ERROR_QUERY_INFO, "订单已支付!");
        }

//        $amount = $this->argv['amount'];
//        global $g_env;
//        if ($g_env != 'ONLINE') {
//            $amount = 1;
//        }

        $channel = $this->argv['channel'];

        $user_data = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $user_data['city_id'];

        $fee_info = $order_info['fee_info'];

        //优惠
        if (!empty($this->argv['coup_id'])){
            $coupon_info = (new CouponModel())->query_info($this->argv['coup_id']);
            $couopon_amount = (new CouponModel())->coupon_amount($coupon_info);
            if ($couopon_amount >0){
                if ($coupon_info['type'] == 1) {
                    if ($couopon_amount > 0 && $fee_info['no_coupon_fee'] < $couopon_amount) {
                        $couopon_amount = $fee_info['no_coupon_fee'];
                    }

                    $fee_info['coupon_id'] = $coupon_info['id'];
                    $fee_info['coupon_metadata'] = $coupon_info['metadata'];
                    $fee_info['coupon_fee'] = $couopon_amount;
                } elseif ($coupon_info['type'] == 2) {
                    $calc_amount = $fee_info['no_coupon_fee'] - ceil($couopon_amount/100*$fee_info['no_coupon_fee']);
                    if ($calc_amount > 0 && $fee_info['no_coupon_fee'] < $calc_amount) {
                        $calc_amount = $fee_info['no_coupon_fee'];
                    }
                    else{
                        $calc_amount = 0;
                    }

                    $fee_info['coupon_id'] = $coupon_info['id'];
                    $fee_info['coupon_metadata'] = $coupon_info['metadata'];
                    $fee_info['coupon_fee'] = $calc_amount;
                }
            }
        }


        $fee_info['total'] -= $fee_info['coupon_fee'];
        if ($fee_info['total'] < 0){
            $fee_info['total'] = 0;
        }

        $tmpamount = $fee_info['total'];

        if ($fee_info['total'] > $user_data['balance']){
            if ($user_data['balance'] >0){
                $tmpamount = $fee_info['total'] - $user_data['balance'];
            }

            $ret = null;
            if($tmpamount > 0){
                $may_amount = 0;
                if ($tmpamount > 0){
                    $now = date('Y-m-d H:i:s');
                    $begin_time = "2020-05-01 00:00:00";
                    $end_time = "2020-05-05 23:59:59";

                    if((strtotime($now) - strtotime($begin_time) >=0)&&(strtotime($now) - strtotime($end_time) <=0)){
                        $may_amount = common::get_may_amount();
                        $this->resp['may_amount'] = $may_amount;
                    }
                }

                if ($channel == 'wxapp'){
                    $ret = (new UserChargeRideOrderModel())->submit_wxapp($order_info['city_id'], $user_data, $tmpamount,$order_id,$this->argv['coup_id'],$may_amount);
                }
                else{
                    $ret = (new UserChargeRideOrderModel())->submit_aliapp($order_info['city_id'], $user_data, $tmpamount,$order_id,$this->argv['coup_id'],$may_amount);
                }
            }

            $this->resp['is_wallet'] = 0;
            $this->resp['info'] = $ret;
        }
        else {
            //余额结账
            //优惠
            $fee_info['balance_fee'] = $fee_info['total'];

            (new UserModel())->incr_balance($order_info['user_id'], 0 - $fee_info['total']);


            $data = [
                'coupon_id' => $fee_info['coupon_id'],
                'coupon_metadata' => $fee_info['coupon_metadata'],
                'distance' => $fee_info['distance'],
                'is_flush' => $fee_info['is_flush'],
                'paid_amount' => $fee_info['total'],
                'fee_info' => $fee_info,
                'violation_fine' => $fee_info['npa_fee'] + $fee_info['osvc_fee'],
                'is_pay'=>1,
            ];


            $where = [
                'id' => $order_id,
            ];


            Db::table('tb_user_ride_order')->where($where)->update($data);
            //hisql::update('tb_user_ride_order', $data, $where);

            if($data['is_pay'] == 1){
                //支付完成
                (new PayModel())->add_record($city_id, $order_info['user_id'], ORDER_TYPE_USER_RIDE, $order_id, PAY_GATEWAY_WALLET, $fee_info['total']);
            }

            if ($fee_info['npa_fee'] > 0 || $fee_info['osvc_fee'] > 0) {
                (new UserModel())->incr_violation_count($order_info['user_id']);
            }

            if ($data['coupon_id'] && $data['is_pay'] == 1) {
                (new CouponModel())->perform($data['coupon_id'],$order_id);

                //添加日志
                if($fee_info['coupon_fee'] >0)
                    (new StatModel())->user_ride_order_amount_incr($order_info['city_id'], $order_info['create_time'], -$fee_info['coupon_fee'],$order_info['start_svca_id']);
            }

            if ($data['is_pay'] == 1){
                $now = date('Y-m-d H:i:s');
                $begin_time = "2020-05-01 00:00:00";
                $end_time = "2020-05-05 23:59:59";

                if((strtotime($now) - strtotime($begin_time) >=0)&&(strtotime($now) - strtotime($end_time) <=0)){
                    if($data['is_pay'] == 1){
                        $may_amount = common::get_may_amount();
                        (new CouponModel())->create_coupon_May_Day($may_amount,$order_info['user_id'],'五一感恩前行');
                        $this->resp['may_amount'] = $may_amount;
                    }
                }
            }

            $this->resp['is_wallet'] = 1;
        }

        return $this->ret_resp();
    }


    function charge_for_giftAction()
    {
        $this->paramlist = [
            'phone' => 'string',
            'amount' => 'int',
            'remark' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info_by_phone($this->argv['phone']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        (new UserChargeModel())->present_to($this->city_id, $userinfo, $this->argv['amount'], $this->argv['remark']);

        return $this->ret_resp();
    }

    function membership_for_giftAction()
    {
        $this->paramlist = [
            'phone' => 'string',
            'days' => 'int',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info_by_phone($this->argv['phone']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        $membership_expire_time = (new UserMembershipOrderModel())->gift_day_membership($userinfo, $this->argv['days']);

        (new UserModel())->set_membership_expire_time($userinfo['id'], $membership_expire_time);

        return $this->ret_resp();
    }

    function coupon_for_giftAction()
    {
        $this->paramlist = [
            'phone' => 'string',
            'amount' => 'int',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info_by_phone($this->argv['phone']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        (new CouponModel())->coupon_for_gift_type_1($userinfo['id'],$this->argv['amount'],'系统赠送');

        return $this->ret_resp();
    }

    function coupon_for_gift2Action()
    {
        $this->paramlist = [
            'phone' => 'string',
            'amount' => 'int',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info_by_phone($this->argv['phone']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        $duration = 24*7*3600*30;
        (new CouponModel())->coupon_for_type_2($userinfo['id'],$this->argv['amount'],$duration,'系统赠送');

        return $this->ret_resp();
    }

    function membership_for_freeAction()
    {
        $this->paramlist = [
            'phone' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info_by_phone($this->argv['phone']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        if (!empty($userinfo['use_free_endtime'])){
            $this->throw_myexception(ERROR_QUERY_INFO, "已经有免费骑行卡了!");
        }

        $membership_expire_time = (new UserMembershipOrderModel())->add_free_membership($userinfo);

        (new UserModel())->set_membership_free_endtime($userinfo['id'], $membership_expire_time);

        return $this->ret_resp();
    }

    function membership_for_luckyAction()
    {
        $this->paramlist = [
            'phone' => 'string',
            'day' => ['optint',360]
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info_by_phone($this->argv['phone']);
        if (empty($userinfo)) {
            $this->throw_myexception(ERROR_QUERY_INFO, "获取用户信息失败!");
        }

        if (!empty($userinfo['use_free_endtime'])){
            $this->throw_myexception(ERROR_QUERY_INFO, "已经有免费骑行卡了!");
        }

        $membership_expire_time = (new UserMembershipOrderModel())->add_lucky_membership($userinfo,$this->argv['day']);

        (new UserModel())->set_membership_free_endtime($userinfo['id'], $membership_expire_time);

        return $this->ret_resp();
    }
    //骑行卡
    function submit_wxmp_ridecardAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        //$price_rule = $this->get_price_rule($city_id, $svca['id']);
        if ($userinfo['balance'] < 0) {
            $this->throw_myexception(ERROR_PAY_FOR_LAST_ORDER_FIRST, "您的账户余额不足，请充值!");
        }

        $order_count = (new UserRadingOrderModel())->get_user_unfinished_order_count($userinfo['id']);
        if ($order_count > 0) {
            $this->throw_myexception(X_ERROR, "您有进行中的订单或者未支付的订单!");
        }

        $cd = [
            'user_id' => $userinfo['id'],
            'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
            'is_use' => 1,
        ];

        $order_list = (new UserRideCardOrderModel())->query_my_list($cd, 0, 1);
        if (!empty($order_list)){
            foreach ($order_list as $e) {
                if ($e['free_count'] != 0)
                    $this->throw_myexception(X_ERROR, "您已经有正在使用的骑行卡，请使用完再购买！");
            }
        }

        $ret = (new UserRideCardOrderModel())->submit_wxmp($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_alipay_ridecardAction()
    {

        //hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        if ($userinfo['balance'] < 0) {
            $this->throw_myexception(ERROR_PAY_FOR_LAST_ORDER_FIRST, "您的账户余额不足，请充值!");
        }

        $order_count = (new UserRadingOrderModel())->get_user_unfinished_order_count($userinfo['id']);
        if ($order_count > 0) {
            $this->throw_myexception(X_ERROR, "您有进行中的订单或者未支付的订单!");
        }

        $cd = [
            'user_id' => $userinfo['id'],
            'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
            'is_use' => 1,
        ];
        $order_list = (new UserRideCardOrderModel())->query_my_list($cd, 0, 1);
        if (!empty($order_list)){
            if ($order_list[0]['free_count'] != 0)
                $this->throw_myexception(X_ERROR, "您已经有正在使用的骑行卡，请使用完再购买！");
        }

        $ret = (new UserRideCardOrderModel())->submit_alipay($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    //骑行卡
    function submit_wxmp_ridecardappAction()
    {
       // hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        //$price_rule = $this->get_price_rule($city_id, $svca['id']);
        if ($userinfo['balance'] < 0) {
            $this->throw_myexception(ERROR_PAY_FOR_LAST_ORDER_FIRST, "您的账户余额不足，请充值!");
        }

        $order_count = (new UserRadingOrderModel())->get_user_unfinished_order_count($userinfo['id']);
        if ($order_count > 0) {
            $this->throw_myexception(X_ERROR, "您有进行中的订单或者未支付的订单!");
        }

        $cd = [
            'user_id' => $userinfo['id'],
            'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
            'is_use' => 1,
        ];

        $order_list = (new UserRideCardOrderModel())->query_my_list($cd, 0, 1);
        if (!empty($order_list)){
            foreach ($order_list as $e) {
                if ($e['free_count'] != 0)
                    $this->throw_myexception(X_ERROR, "您已经有正在使用的骑行卡，请使用完再购买！");
            }
        }

        $ret = (new UserRideCardOrderModel())->submit_wxapp($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    function submit_alipay_ridecardappAction()
    {

        //hilog::set_pay_log_path();
        $this->paramlist = [
            'id' => 'int',
            'user_coordinate' => 'optfloatarray',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];

        if (empty($city_id) && isset($this->argv['user_coordinate'])) {
            $city_id = (new ServiceAreaModel())->coordinate_to_city_id($this->argv['user_coordinate']);
        }

        if ($userinfo['balance'] < 0) {
            $this->throw_myexception(ERROR_PAY_FOR_LAST_ORDER_FIRST, "您的账户余额不足，请充值!");
        }

        $order_count = (new UserRadingOrderModel())->get_user_unfinished_order_count($userinfo['id']);
        if ($order_count > 0) {
            $this->throw_myexception(X_ERROR, "您有进行中的订单或者未支付的订单!");
        }


        $cd = [
            'user_id' => $userinfo['id'],
            'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
            'is_use' => 1,
        ];
        $order_list = (new UserRideCardOrderModel())->query_my_list($cd, 0, 1);
        if (!empty($order_list)){
            if ($order_list[0]['free_count'] != 0)
                $this->throw_myexception(X_ERROR, "您已经有正在使用的骑行卡，请使用完再购买！");
        }

        $ret = (new UserRideCardOrderModel())->submit_aliapp($city_id, $userinfo, $this->argv['id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    //可购买列表
    function ridecard_listAction(){
        $this->paramlist = [
            'token' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = null;
        if(isset($userinfo['city_id'])){
            $city_id = $userinfo['city_id'];
        }

        $this->resp['list'] = (new UserRideCardOrderModel())->card_list($city_id);

        return $this->ret_resp();
    }

    //我的骑行卡
    function myridecard_uselistAction(){
        $this->paramlist = [
            'token' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $user_info = ApiOper::instance()->userinfo();

        $cd = [
            'user_id' => $user_info['id'],
            'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
            'is_use' => 1,
        ];
        $this->resp['list'] = (new UserRideCardOrderModel())->query_my_list($cd, 0, 20);

        return $this->ret_resp();
    }

    //我的购买记录
    function myridecard_buylistAction(){
        $this->paramlist = [
            'token' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $user_info = ApiOper::instance()->userinfo();

        $cd = [
            'user_id' => $user_info['id'],
            'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
        ];
        $this->resp['list'] = (new UserRideCardOrderModel())->query_my_list($cd, 0, 30);

        return $this->ret_resp();
    }

    function userridecard_listAction(){
        $this->paramlist = [
            'token' => 'string',
            'user_id' => 'string',
            'pno' => 'optint',
            'psize' => 'optint',
        ];
        $this->check_params();
        $this->check_token();

        $cd = [
            'user_id' => $this->argv['user_id'],
            'order_state' => USER_RIDECARD_ORDER_STATE_FINISHED,
        ];
        $l = (new UserRideCardOrderModel())->query_my_list($cd, $this->argv['pos'], $this->argv['limit']);
        $this->resp['list'] = $l;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();

    }

    //城市
    function chargeNumsAction(){

        try
        {
            $this->paramlist=[
                'token' => 'string',
                'city_id' => ['optstring',null],
            ];

            $this->check_params();
        }
        catch (Exception $e){
            $this->paramlist=[
                'token' => 'string',
            ];
            $this->check_params();
        }

        $this->check_token();

        $city_id = null;

        if (isset($this->argv['city_id']))
        {
            $city_id = $this->argv['city_id'];
        }



        $this->resp['list'] = (new UserChargeModel())->get_charge_list($city_id);

        return $this->ret_resp();
    }

    function wxcharge_profitAction()
    {
        //hilog::set_pay_log_path();
        $this->paramlist =[
            'token' => 'string',
        ];

        $this->check_params();
        $this->check_token();

        $userinfo = (new UserModel())->query_info(ApiOper::instance()->userinfo()['id']);
        $city_id = $userinfo['city_id'];
        $amount = 10;

        $ret = (new UserChargeModel())->submit_wxmp_profit($city_id,$userinfo,$amount);

        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }

    //分账
    function profit_notifyAction()
    {
        //hilog::set_pfx('ali');
        $this->paramlist =[
            'token' => 'string',
            'city_id' => 'string',
            'total_amount' => 'int',
            'transaction_id' =>'string',
            'order_type' => 'string',
            'gate_way' => 'string',
            'origin_id' => 'string',
        ];

        $this->check_params();
        $this->check_token();

//        $max_try = (new StatModel())->get_profit_error($this->argv['origin_id']);
//        if ($max_try < 1){
//            $ret = (new PayModel())->profitshare_order($this->argv['gate_way'],$this->argv['city_id'],$this->argv['origin_id'],$this->argv['order_type'],$this->argv['total_amount'],$this->argv['transaction_id']);
//
//            if (empty($ret)){
//                (new StatModel())->incr_profit_error($this->argv['origin_id']);
//
//                //再次尝试分账
//                (new PayModel())->timer_profitshare($this->argv['city_id'],$this->argv['total_amount'],$this->argv['transaction_id'],$this->argv['order_type'],$this->argv['gate_way'],$this->argv['origin_id']);
//            }
//            $this->resp['info'] = $ret;
//        }


        $ret = (new PayModel())->profitshare_order($this->argv['gate_way'],$this->argv['city_id'],$this->argv['origin_id'],$this->argv['order_type'],$this->argv['total_amount'],$this->argv['transaction_id']);
        $this->resp['info'] = $ret;

        return $this->ret_resp();
    }


    //分账list
    function profit_listAction(){
        $this->paramlist =[
            'token' => 'string',
            'city' => 'optstring',                  //城市id ,所有城市为ALL
            'begin_time' => 'optstring',            //搜索栏开始时间
            'end_time' =>'optstring',               //结束时间
            'order_type' => 'optstring',            //交易类型 USER_CHARGE 充值 MEMBERSHIP 会员 USER_RIDE_CHARGE骑行支付 RIDECARD 骑行卡
            'gateway' => 'optstring',               //支付方式支付方式 WXPAY ALIPAY
            'pno' => 'optint',
            'psize' => 'optint',
        ];

        $this->check_params();
        $this->check_token();


        $list = (new SharePayRecordModel())->query_list($this->argv,$this->argv['pos'],$this->argv['limit']);
        $this->resp['list'] = $list;
        $this->resp['total'] = hisql::query_count();

        return $this->ret_resp();
    }
}
